﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace InstitutionAssitant
{
    /// <summary>  
    /// ClassName:frmMain
    /// Version:1.0
    /// Date:2017-03-21
    /// Author:seanouyang
    /// </summary>  
    /// <remarks>  
    /// 本类是一WinForm 窗体,本窗体主要为系统主界面
    /// </remarks>
    public partial class frmMain : DevComponents.DotNetBar.RibbonForm
    {
        #region 01.自定义属性
        private Dictionary<string,string> tablItem = new Dictionary<string,string>();
        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        public frmMain()
        {
            InitializeComponent();            
            // 01 设置窗体类别为 MDI
            this.IsMdiContainer = true;
            // 02 设置窗体大小和位置
            this.Top = 0;
            this.Left = 0;
            this.Width = Screen.PrimaryScreen.WorkingArea.Width;
            this.Height = Screen.PrimaryScreen.WorkingArea.Height;
            // 03 相关信息初始化
            this.Icon = AppInfo.m_iconApp;
            this.Text = AppInfo.m_strAppName;
        }

        #region 01.自定义方法
        /// <summary>
        /// 判断是否有存在相同类窗体在tab页打开，防止打开多个同样的子窗体
        /// </summary>
        /// <param name="strTabName">窗体名称</param>
        /// <returns>如果存在返回true,否则返回false</returns>
        private bool _isTabOpen(string strTabName)
        {
            bool bIsOpened = false;
            tabStrip1.Visible = true;
            pbMain.Visible = false;
            // 页循环比对页名称
            foreach (TabItem tabItem in tabStrip1.Tabs)
            {
                if (strTabName.Equals(tabItem.Text.Trim()))
                {
                    bIsOpened = true;
                    tabStrip1.SelectedTab = tabItem;
                    break;
                }
            }
            return bIsOpened;
        }

        /// <summary>
        /// 清除所有打开的tabs
        /// </summary>
        public void _clearTabs()
        {
            foreach (Form frmTemp in this.MdiChildren)
            {
                frmTemp.Close();
            }
        }

        /// <summary>
        /// 显示信息类窗体通用操作
        /// <param name="nKind">类别</param>
        private void _showQueryInfo(int nKind)
        {
            string tabName = "";
            switch (nKind)
            {
                case 10:
                    tabName = "溯源入库";
                    break;
                case 11:
                    tabName = "入库信息";
                    break;
                case 12:
                    tabName = "订单信息";
                    break;
                case 13:
                    tabName = "配送信息";
                    break;
                case 21:
                    tabName = "药品对码";
                    break;
                case 22:
                    tabName = "配送企业对码";
                    break;
                case 14:
                    tabName = "药库出库";
                    break;
                case 15:
                    tabName = "退库单据";
                    break;
                case 16:
                    tabName = "药房入库";
                    break;
                case 17:
                    tabName = "药房出库";
                    break;
                case 18:
                    tabName = "药房退库";
                    break;
                default:
                    return;
            }
            Form frm = new Form();
            if (!_isTabOpen(tabName))
            {
                switch (nKind)
                {
                    case 10:
                        frm = new frmDeliveryToStockIn();
                        frm.Text = string.Format(" {0} ", tabName);
                        frm.MdiParent = this;
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    case 11:
                        frm = new frmStockIn();
                        frm.Text = string.Format(" {0} ", tabName);
                        frm.MdiParent = this;
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    case 12:
                        frm = new frmOrder();
                        frm.Text = string.Format(" {0} ", tabName);
                        frm.MdiParent = this;
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    case 13:
                        frm = new frmDelivery();
                        frm.Text = string.Format(" {0} ", tabName);
                        frm.MdiParent = this;
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    case 14:
                        frm = new frmStockOut();
                        frm.Text = string.Format(" {0} ", tabName);
                        frm.MdiParent = this;
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    case 15:
                        frm = new frmFacReturn();
                        frm.Text = string.Format(" {0} ", tabName);
                        frm.MdiParent = this;
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    case 16:
                        frm = new frmPharIn();
                        frm.Text = string.Format(" {0} ", tabName);
                        frm.MdiParent = this;
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    case 17:
                        frm = new frmPharOut();
                        frm.Text = string.Format(" {0} ", tabName);
                        frm.MdiParent = this;
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    case 18:
                        frm = new frmPharReturn();
                        frm.Text = string.Format(" {0} ", tabName);
                        frm.MdiParent = this;
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    case 21:
                        frm = new frmQuery_MedicineCodeCheck();
                        frm.Text = string.Format(" {0} ", tabName);
                        frm.MdiParent = this;
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;
                    case 22:
                        frm = new frmQuery_EnterpriseCodeCheck();
                        frm.Text = string.Format(" {0} ", tabName);
                        frm.MdiParent = this;
                        frm.WindowState = FormWindowState.Maximized;
                        frm.Show();
                        break;    
                }
            }
        }
       
        /// <summary>
        /// 系统登录
        /// </summary>
        private void _login()
        {
            // 01 登录窗体
            frmLogin frm = new frmLogin();
            frm.ShowIcon = false;
            frm.ShowInTaskbar = false;
            frm.TopMost = true;
            frm.ShowDialog();
            // 02 登录成功,重新初始化，否则退出系统
            if (AppInfo.m_bLogin)
            {
                _clearTabs();
                this.Text = string.Format("{0}【单位名称：{1}({2})-{3}】", AppInfo.m_strAppName, AppInfo.m_UserInfo.m_strDeptName, AppInfo.m_UserInfo.m_strDeptCode, AppInfo.m_UserInfo.m_strName);
                this.RibbonControl.TitleText = this.Text;
            }
            else
            {
                this.Close();
            }
        }
        #endregion  

        #region 02.系统窗体控件事件方法
        
        private void frmMain_Load(object sender, EventArgs e)
        {
            // 01 初始化登录员
            this.Text = string.Format("{0}【单位名称：{1}({2})-{3}】", AppInfo.m_strAppName, AppInfo.m_UserInfo.m_strDeptName, AppInfo.m_UserInfo.m_strDeptCode, AppInfo.m_UserInfo.m_strName);
            this.RibbonControl.TitleText = this.Text;
            this.biOrder.Visible = AppConfig.m_bIsHaveOrder;
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 如果未登录，不进行退出提示
            if (AppInfo.m_bLogin)
            {
                DialogResult result = CommFun._messageBoxShow("是否确定退出本系统?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    this.Dispose();
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // 计时处理，显示时间在statusBar上
            lblDatetime.Text = string.Format("当前时间：{0}", DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss"));
        }

        private void tabStrip1_TabRemoved(object sender, EventArgs e)
        {
            // 01 Tab页关闭完所有页后显示主页图片
            if (tabStrip1.Tabs.Count == 0)
            {
                pbMain.Visible = true;
            }
        }
        #endregion

        #region 03.菜单功能项:系统操作
        private void biSetup_Click(object sender, EventArgs e)
        {
            frmSetup frm = new frmSetup();
            frm.ShowIcon = false;
            frm.ShowInTaskbar = false;
            frm.ShowDialog();
        }

        private void biSystem_PasswordChange_Click(object sender, EventArgs e)
        {
            frmPasswordChange frm = new frmPasswordChange();
            frm.ShowIcon = false;
            frm.ShowInTaskbar = false;
            frm.ShowDialog();
        }

        private void biSystem_About_Click(object sender, EventArgs e)
        {
            // FrmAbout 窗体显示
            frmAbout frm = new frmAbout();
            frm.ShowIcon = false;
            frm.ShowInTaskbar = false;
            frm.TopMost = true;
            frm.ShowDialog();
        }

        private void biSystem_Logout_Click(object sender, EventArgs e)
        {
            // 01 系统注销
            DialogResult result = CommFun._messageBoxShow("是否确定要注销当前用户?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.No)
            {
                return;
            }
            // 02 重新进行登录
            _login();
        }

        private void biSystem_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion
        
        #region 04.菜单功能项业务操作
        private void biDeliveryToStockIn_Click(object sender, EventArgs e)
        {
            _showQueryInfo(10);
        }
        private void btiStockIn_Click(object sender, EventArgs e)
        {
            _showQueryInfo(11);
        }
        private void btiStockOut_Click(object sender, EventArgs e)
        {
            _showQueryInfo(14);
        }
        private void btiFacReturn_Click(object sender, EventArgs e)
        {
            _showQueryInfo(15);
        }
        
        private void btiPharIn_Click(object sender, EventArgs e)
        {
            _showQueryInfo(16);
        }
        private void btiPharReturn_Click(object sender, EventArgs e)
        {
            _showQueryInfo(18);
        }
        private void btiPharOut_Click(object sender, EventArgs e)
        {
            _showQueryInfo(17);
        }
        private void biLocalOrder_Click(object sender, EventArgs e)
        {
            _showQueryInfo(12);
        }

        private void biDelivery_Click(object sender, EventArgs e)
        {
            _showQueryInfo(13);
        }        

        private void biMedicineCheck_Click(object sender, EventArgs e)
        {
            _showQueryInfo(21);
        }
        private void biEnterpriseCheck_Click(object sender, EventArgs e)
        {
            _showQueryInfo(22);
        }
        #endregion

        private void btiPharIn_Click_1(object sender, EventArgs e)
        {
            _showQueryInfo(16);
        }

        private void btiStockOut_Click_1(object sender, EventArgs e)
        {
            _showQueryInfo(14);
        }

        private void btiPharReturn_Click_1(object sender, EventArgs e)
        {
            _showQueryInfo(18);
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            //判断是否有新的程序版本
            //_checkVersion();
        }
        private void _checkVersion()
        {
            string url = DbHelper._getAutoUpdateAddress();  // + "/Api/Scheme/GetLatestWinformVersion";
            if(!url.Equals("")&&!url.Equals("http://"))
            {
                url+= "/Api/Scheme/GetLatestWinformVersion";
                string resCode = HisInterFace.Post(url, "");
                int _currentVer = int.Parse(DbHelper._getCurrentVersion());
                if (!resCode.Equals(""))
                {
                    JObject jo = (JObject)JsonConvert.DeserializeObject(resCode);
                    int _newVersion = int.Parse(jo["VersionCode"].ToString());
                    int _IsForceUpdate = int.Parse(jo["IsForceUpdate"].ToString());
                    if (_newVersion > _currentVer) //有新版本
                    {
                        if (_IsForceUpdate == 1) //必须强制更新
                        {
                            _DownloadNewVersion(_newVersion);
                        }
                        else
                        {
                            if (CommFun._messageBoxShow("程序有新的版本，是否下载更新！", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)
                            {
                                _DownloadNewVersion(_newVersion);
                            }
                            else
                            {
                                timer2.Enabled = false;
                            }
                        }
                    }
                }
            }                        
        }
        private void _DownloadNewVersion(int _newVersion)
        {
            string url = DbHelper._getAutoUpdateAddress() + "/Api/Scheme/DownloadVersionPackage?hasValue=";
            string downloadurl = HisInterFace.Get(url);
            string filename = _getDownloadFile(downloadurl);
            string files = AppDomain.CurrentDomain.BaseDirectory + "\\" + filename;
            WebClient wc = new WebClient();
            string currentExecutable = Process.GetCurrentProcess().MainModule.FileName;
            wc.DownloadFile(downloadurl, files);
            //File.Copy(files, currentExecutable, true);
            DbHelper._setCurrentVersion(_newVersion.ToString());
            Process.Start(currentExecutable);
        }
        private string _getDownloadFile(string downurl)
        {
            string[] _filearr = downurl.Split('/');
            if (_filearr.Length > 0)
                return _filearr[_filearr.Length - 1];
            else
                return "";
        }
    }
}